/**
 * @description: bindEvent
 * @author: huen2015
 */

import { IFn } from './types'

function bindEvent(type: string, el: Element, fn: IFn, selector?: string) {
	el.addEventListener(type, function (this: any, e: Event) {
		if (selector) {
			const target = e.target
			if (target) {
				if ((target as Element).matches(selector)) {
					fn.call(target, e)
				}
			}
		} else {
			fn.call(this, e)
		}
	})
}

const bindEventDom = document.querySelector('#bindEvent')
const bindEventButtonDom = document.querySelector('#bindEventButton')
if (bindEventDom) {
	// 事件委托
	bindEvent(
		'click',
		bindEventDom,
		function (this: any, e: PointerEvent) {
			console.log('this', this)
			console.log('e', e)
		},
		'a',
	)
}
if (bindEventButtonDom) {
	// 非事件委托
	bindEvent(
		'click',
		bindEventButtonDom,
		function (this: any, e: PointerEvent) {
			console.log('this', this)
			console.log('e', e)
		},
	)
}

export { bindEvent }
